package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import io.netty.util.internal.ObjectUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component// 注册到spring容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override//插入数据自动填充
    public void insertFill(MetaObject metaObject) {
//        this.strictInsertFill(metaObject,"createBy",String.class,getLoginUserId().toString());//创建者
//        this.strictInsertFill(metaObject,"createTime",Date.class, DateUtils.getNowDate());//创建时间
        strictInsertFill(metaObject, "createTime", Date.class, new Date());
        strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUserId()));
    }

    @Override//更新数据自动填充
    public void updateFill(MetaObject metaObject) {
//        this.strictUpdateFill(metaObject,"updateBy",String.class,getLoginUserId().toString());//更新者
//        this.strictUpdateFill(metaObject,"updateTime",Date.class, DateUtils.getNowDate());//更新时间
        strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(getLoginUserId()));
    }
    public Long getLoginUserId(){//获取登录用户id
        LoginUser loginUser = SecurityUtils.getLoginUser();//方法调用获取登录用户信息
        if (ObjectUtils.isNotEmpty(loginUser)){
            return loginUser.getUserId();
        }
        return 1L;
    }
}
